package cn.zzuli.securitydemo1.service;

import cn.zzuli.securitydemo1.dao.UserMapper;
import cn.zzuli.securitydemo1.entity.Users;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Date: 2020/12/27 14:08
 * @Author: 绯色下午茶
 * @Description:
 */
@Service("myUserDetailService")
public class MyUserDetailService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<Users> wrapper=  new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);
        if (users == null) {
//            数据库没有用户名
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println("当前代码运行时间是： " + System.currentTimeMillis());

        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("consumer,ROLE_consumer");

        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPwd()) ,list);
    }
}
